package com.sinodata.bsm.center.dao.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.sinodata.bsm.center.bean.Condition;
import com.sinodata.bsm.center.bean.EventCorrelationPolicyBean;
import com.sinodata.bsm.center.bean.Page;
import com.sinodata.bsm.center.dao.BaseDao;
import com.sinodata.bsm.center.dao.EventCorrelationDao;
import com.sinodata.bsm.common.vo.EventCorrelation;
import com.sinodata.bsm.common.vo.EventCorrelationPolicy;

/**
 * <p>
 * Description: 事件相关性，存储事件关联数据DAO
 * </p>
 *
 * @author dongyushi
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-6-14 PM 4:53:01     dongyushi        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
@Repository
public class EventCorrelationDaoImpl extends BaseDao implements EventCorrelationDao {

    //private final static Logger logger = LoggerFactory.getLogger(EventCorrelationDaoImpl.class);

    /*
     * (non-Javadoc)
     * @see com.sinodata.bsm.center.dao.EventCorrelationDao#findEventCorrelationPolicyByPage(com.sinodata.bsm.center.bean.Page)
     */
    @Override
    public Page<EventCorrelationPolicyBean> findEventCorrelationPolicyByPage(Page<EventCorrelationPolicyBean> page, Condition condition) {
        page.setTotal(getTotal(condition));
        StringBuffer sql = new StringBuffer("select ecp.id,");
        sql.append("ecp.name,");
        sql.append("ecp.main_event_type,");
        sql.append("et.name eventTypeName,");
        sql.append("ecp.policy_type,");
        sql.append("ecp.status,");
        sql.append("ecp.delay,");
        sql.append("ecp.extend_config,");
        sql.append("ecp.memo");
        sql.append(" from event_correlation_policy ecp");
        sql.append(" left outer join event_type et on ecp.main_event_type = et.id");
        sql.append(" where 1 = 1 ");
        sql.append(getConditonSql(condition));
        Query query = getSession().createSQLQuery(sql.toString()).setFirstResult(page.getFirstResultNo()).setMaxResults(page.getPageSize());
        @SuppressWarnings("unchecked")
        List<Object[]> list = query.list();
        List<EventCorrelationPolicyBean> listResult = new ArrayList<EventCorrelationPolicyBean>();
        for (Object[] o : list) {
            EventCorrelationPolicyBean eventCorrelationPolicyBean = new EventCorrelationPolicyBean();
            EventCorrelationPolicy eventCorrelationPolicy = new EventCorrelationPolicy();
            if (o[0] != null) {
                eventCorrelationPolicy.setId(Long.valueOf(String.valueOf(o[0])));
            }
            if (o[1] != null) {
                eventCorrelationPolicy.setName(String.valueOf(o[1]));
            }
            if (o[2] != null) {
                eventCorrelationPolicy.setMainEventType(Long.valueOf(String.valueOf(o[2])));
            }
            if (o[3] != null) {
                eventCorrelationPolicyBean.setMainEventTypeName(String.valueOf(o[3]));
            }
            if (o[4] != null) {
                eventCorrelationPolicy.setPolicyType(String.valueOf(o[4]));
            }
            if (o[5] != null) {
                eventCorrelationPolicy.setStatus(String.valueOf(o[5]));
            }
            if (o[6] != null) {
                eventCorrelationPolicy.setDelay(Integer.valueOf(String.valueOf(o[6])));
            }
            if (o[7] != null) {
                eventCorrelationPolicy.setExtendConfig(String.valueOf(o[7]));
            }
            if (o[8] != null) {
                eventCorrelationPolicy.setMemo(String.valueOf(o[8]));
            }
            eventCorrelationPolicyBean.setEventCorrelationPolicy(eventCorrelationPolicy);
            listResult.add(eventCorrelationPolicyBean);
        }
        page.setRows(listResult);
        return page;
    }

    /**
     * 拼接查询条件
     * 
     * @param condition
     * @return
     */
    private StringBuilder getConditonSql(Condition condition) {
        StringBuilder hql = new StringBuilder();
        Map<String, String> condMap = condition.getWhere();
        if (condMap.size() != 0) {
            hql.append(" and ( ");
            Iterator<String> keyItr = condMap.keySet().iterator();
            while (keyItr.hasNext()) {
                String key = keyItr.next();
                hql.append("ecp.").append(key).append(" like '%" + condMap.get(key).substring(1, condMap.get(key).lastIndexOf("'")) + "%'");
                hql.append(" and ");
            }
            hql.delete(hql.lastIndexOf(" and "), hql.length()).append(" ) ");
        }
        return hql;
    }

    /**
     * 获取总数
     * 
     * @return
     */
    private int getTotal(Condition condition) {
        StringBuilder hql = new StringBuilder(" select count(*) from event_correlation_policy ecp where 1=1 ");
        hql.append(getConditonSql(condition));
        Query query = this.getSession().createSQLQuery(hql.toString());
        return ((BigDecimal) query.list().iterator().next()).intValue();
    }

    /*
     * (non-Javadoc)
     * @see com.sinodata.bsm.center.dao.EventCorrelationDao#findByMainAndSubEvent(java.lang.Long, java.lang.Long)
     */
    @Override
    public List<EventCorrelation> findByMainAndSubEvent(Long mainEventId, Long subEventId) {
        String hql = "from EventCorrelation where mainEventId = " + mainEventId + " and eventId = " + subEventId;
        return this.getSession().createQuery(hql).list();
    }

    @Override
    public int getByName(String name) {
        StringBuilder hql = new StringBuilder(" select count(*) from EventCorrelationPolicy where name = '" + name + "'");
        Query query = this.getSession().createQuery(hql.toString());
        return ((Long) query.list().iterator().next()).intValue();
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.dao.EventCorrelationDao#findByMainEvent(java.lang.Long)
     */
    @Override
    public List<EventCorrelation> findByMainEvent(Long mainEventId) {
        String sql = "select distinct * from Event_Correlation t  start with t.main_event_id = " + mainEventId + " connect by prior t.event_id = t.main_event_id";

        Query query = getSession().createSQLQuery(sql.toString());
        @SuppressWarnings("unchecked")
        List<Object[]> list = query.list();
        List<EventCorrelation> listResult = new ArrayList<EventCorrelation>();
        for (Object[] o : list) {
            EventCorrelation eventCorrelation = new EventCorrelation();
            if (o[0] != null) {
                eventCorrelation.setId(Long.valueOf(String.valueOf(o[0])));
            }
            if (o[1] != null) {
                eventCorrelation.setEventId(Long.valueOf(String.valueOf(o[1])));
            }
            if (o[2] != null) {
                eventCorrelation.setPolicyId(Long.valueOf(String.valueOf(o[2])));
            }
            if (o[3] != null) {
                eventCorrelation.setMainEventId(Long.valueOf(String.valueOf(o[3])));
            }
            listResult.add(eventCorrelation);
        }
        return listResult;
    }
}